<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class SiteconfigController extends Controller
{
    public function __construct()
    {
        $this->middleware('grant:siteconfig');
    }

    public function getMeta(Request $request)
    {
        $data['meta'] = config('site');
        return view('admin/siteconfig/meta', $data);
    }

    public function postSetMeta(Request $request)
    {
        $name = strval($request->input('name'));
        $title = strval($request->input('title'));
        $keywords = strval($request->input('keywords'));
        $description = strip_tags($request->input('description'));
        $logo = config('site.logo');

        $cfg_str = <<<EOF
<?php
return array(
    'name' => '$name',
    'title' => '$title',
    'keywords' => '$keywords',
    'description' => '$description',
    'logo' => '$logo',
);
EOF;
        $cfg_file = realpath(config_path() . DIRECTORY_SEPARATOR . 'site.php');
        if (!file_exists($cfg_file)) {
            return $this->error('配置文件丢失');
        }
        if (file_put_contents($cfg_file, $cfg_str)) {
            return $this->response();
        }
        return $this->error('配置文件写入失败');
    }

    public function getLogo()
    {
        $logo = config('site.logo') ?: 'upload/logo.png';
        return view('admin/siteconfig/logo')->withLogo(url($logo));
    }

    public function postUploadLogo(Request $request)
    {
        $file = $_FILES['file'];
        $fileTypes = ['jpg', 'jpeg', 'gif', 'png'];
        $file_ext = strtolower(pathinfo($file['name'])['extension']);
        if (!in_array($file_ext, $fileTypes)) {
            $result = ['status' => 0, 'msg' => '无效的图片格式'];
            return $this->response($result);
        }

        $target_path = 'upload/logo/';
        $targetPath = public_path($target_path);
        if (!is_dir($targetPath)) {
            if (!mkdir($targetPath, 0777, 1)) {
                $result = ['status' => 0, 'msg' => '无法建立上传目录'];
                return $this->response($result);
            }
        }
        $new_filename = uniqid(mt_rand()) . '.' . $file_ext;
        $result = move_uploaded_file($file['tmp_name'], $targetPath . $new_filename);
        if ($result === false) {
            $result = ['status' => 0, 'msg' => '保存文件失败'];
            return $this->response($result);
        }

        $new_file = $target_path . $new_filename;
        $cfg_file = realpath(config_path('site.php'));
        $cfg_str = file_get_contents($cfg_file);
        $pattern = '/([\s\S]*\'logo\' => \')(.*)(\'[\s\S]*)/s';
        $replacement = '$1' . $new_file . '$3';
        $new_str = preg_replace($pattern, $replacement, $cfg_str);
        file_put_contents($cfg_file, $new_str);
        $result = ['status' => 1, 'url' => asset($new_file)];
        return $this->response($result);
    }
}
